// encrypt-server.js - 支持轨迹数据
const { encrypt, initEncryptor } = require('./sign');
const express = require('express');

const app = express();
app.use(express.json({ limit: '10mb' })); // 增加请求体大小限制

let isReady = false;

// 初始化加密器
initEncryptor().then(() => {
    isReady = true;
    console.log("✓ 加密服务准备就绪");
});

// 加密轨迹数据接口
app.post('/encrypt-trail', (req, res) => {
    if (!isReady) {
        return res.status(503).json({ error: "服务尚未准备就绪" });
    }

    try {
        const trailData = req.body;
        const result = encrypt(trailData);

        res.json({
            success: true,
            originalDataSize: JSON.stringify(trailData).length,
            encrypted: result,
            timestamp: Date.now()
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            error: error.message
        });
    }
});

// 保持原有的坐标加密接口
app.post('/encrypt', async (req, res) => {
    try {
        const coordinate = req.body; // 应该是 {x: 153, y: 5}
        const encrypted = encrypt(coordinate); // 调用 sign.js 的 encrypt 函数

        res.json({
            success: true,
            input: coordinate,
            encrypted: encrypted  // 这应该是76位的结果
        });
    } catch (error) {
        res.json({ success: false, error: error.message });
    }
});

app.listen(3000, () => {
    console.log("加密服务运行在 http://localhost:3000");
    console.log("轨迹加密接口: POST /encrypt-trail");
    console.log("坐标加密接口: POST /encrypt");
});